﻿using CommonClass.CountInfo;
using I_SheepManagement.Infrastructure.Interface;
using I_SheepManagement.Read.API.Application.Command;
using MediatR;

namespace I_SheepManagement.Read.API.Application.CommandHandler
{
    public class SheepCountReadCommandHandler : IRequestHandler<SheepCountReadCommand, List<DeadTaoTrend>>
    {
        private readonly IDeathManagementRepository _deathManagementRepository;
        private readonly IEliminationManagementRepository _eliminationManagementRepository;

        public SheepCountReadCommandHandler(IDeathManagementRepository deathManagementRepository, IEliminationManagementRepository eliminationManagementRepository)
        {
            _deathManagementRepository = deathManagementRepository;
            _eliminationManagementRepository = eliminationManagementRepository;
        }

        public async Task<List<DeadTaoTrend>> Handle(SheepCountReadCommand request, CancellationToken cancellationToken)
        {
            var dateStart = DateTime.Now.AddMonths(-1);
            var deathList = await _deathManagementRepository.GetByFuncListAsync(x => !x.IsDelete);
            var eliminationList = await _eliminationManagementRepository.GetByFuncListAsync(x => !x.IsDelete);
            Dictionary<DateTime, (int, int)> dic = new Dictionary<DateTime, (int, int)>();
            for (DateTime date = dateStart; date <= DateTime.Today; date = date.AddDays(1))
            {
                dic[date] = (
                    deathList.Where(x => Convert.ToDateTime(x.CreateDate).Day == date.Day).Count(),
                    eliminationList.Where(x => Convert.ToDateTime(x.CreateDate).Day == date.Day).Count());
            }
            var deadTaoList = dic
                .Select(x => new DeadTaoTrend
                {
                    Date = x.Key.ToString("MM/dd"),
                    DeathCount = x.Value.Item1,
                    ElinationCount = x.Value.Item2
                }).ToList();
            return deadTaoList;

        }
    }
}
